package org.vectrics.recruiter.struts.admin;

import javax.servlet.jsp.JspException;

import org.apache.log4j.Logger;
import org.vectrics.common.util.StringUtils;
import org.vectrics.location.Location;
import org.vectrics.provider.CoreServiceLocator;
import org.vectrics.struts.VectricsActionData;
import org.vectrics.struts.VectricsStrutsAction;

public class ShowLocationAction extends VectricsStrutsAction {
    private Logger log = Logger.getLogger(this.getClass());

    public ShowLocationAction() {
        //
    }

    @Override
    public String doExecute(final VectricsActionData actionData) throws JspException {

        LocationForm locationForm = new LocationForm();
        actionData.setRequestForm(locationForm);
        locationForm.setParentName("");

        String locationId = actionData.getRequest().getParameter("locationId");
        if (StringUtils.isNullOrBlank(locationId)) {
            log.debug("No locationId passed, assuming we are creating a new location, parentId determines parent location of new location");
            String parentLocationId = actionData.getRequest().getParameter("parentId");
            if (StringUtils.isNullOrBlank(parentLocationId)) {

            } else {
                Location parent = CoreServiceLocator.getLocationService().findLocation(new Long(parentLocationId));
                if (parent != null) {
                    locationForm.setParentName(parent.getName());
                    locationForm.setParentId(parent.getId().toString());

                    if (parent.getTypeCode().equalsIgnoreCase("country")) {
                        locationForm.setTypeCode("state");
                    } else if (parent.getTypeCode().equalsIgnoreCase("state")) {
                        locationForm.setTypeCode("city");
                    }

                }
            }

        } else {
            Location location = CoreServiceLocator.getLocationService().findLocation(new Long(locationId));
            locationForm.setDescription(location.getDescription());
            locationForm.setAbbreviation(location.getAbbreviation());
            locationForm.setName(location.getName());
            locationForm.setId(locationId);
            locationForm.setTypeCode(location.getTypeCode());
            if (location.getParent() != null) {
                locationForm.setParentId(location.getParent().getId().toString());
                locationForm.setParentName(location.getParent().getName());
            }
        }
        boolean isCountry = locationForm.getTypeCode().equalsIgnoreCase("country");
        LocationForm.addLocationTypeCollection(actionData.getLocale(), actionData.getRequest(), isCountry);

        return "success";

    }

}
